<template>
  <div class="specification-detail">
    <!--    地址区域-->
    <van-contact-card
        v-if="chosenContactId"
        type="edit"
        :name="currentContact.name"
        :tel="currentContact.tel"
        @click="handleLinkAreaList"
    />

    <van-contact-card v-else type="add" @click="handleLinkAreaList"/>
    <van-popup v-model="showAreaList" position="right" :style="{ height: '100%', width: '100vw' }">
      <van-nav-bar
          title="地址列表"
          left-arrow
          @click-left="onClickLeft"
      >

      </van-nav-bar>
      <van-address-list
          v-model="chosenContactId"
          :list="list"
          default-tag-text="默认"
          @add="handleAreaListAdd"
          @edit="handleAreaListEdit"
          @select="handleAreaListSelect"

      />
    </van-popup>
    <van-dialog
        v-model="areaListEditShow"
        :title="areaListEditTitle"
        width="6rem"
        :showConfirmButton="false"
    >

      <van-button style="position: absolute; right:10px; top:10px;border:0;font-size:16px;" icon="close" size="small"
                  @click="handleAreaDialog"/>
      <van-address-edit
          :address-info="updateInfo"
          :area-list="areaList"
          show-set-default
          show-search-result
          show-delete
          :detail-rows="1"
          :area-columns-placeholder="['请选择', '请选择', '请选择']"
          @save="handleAddArea"
          @delete="handleDelArea"
      />
    </van-dialog>
    <!--    地址区域-->
    <!-- 商品sku区域-->
    <div class="product-sku-wrapper">
      <div class="pic-price-msg-wrapper">
        <van-image
            width="1.53rem"
            height="1.53rem"
            fit="cover"
            :src="currentSku.pic"
        />
        <div class="price-msg">
          <div class="price-content">
            <span class="icon">￥</span>
            <span class="price">{{ calculatedPrice }}</span>
            <span class="txt">商城价</span>
          </div>
          <div class="sale-content">
            <span class="txt">已售{{ productDetailData.sale }}件</span>
            <span class="segmentation"></span>
            <span class="txt">{{ productDetailData.sale }}+人购买</span>
          </div>
          <div class="nums-content">
            <van-stepper v-model="shopNums" :max="currentSku.stock" integer/>
            <span class="txt">(库存{{ currentSku.stock }})</span>
          </div>
        </div>


      </div>
      <div class="sku-msg-wrapper">
        <!-- 动态渲染规格属性 -->
        <div class="sku-item" v-for="spec in specList" :key="spec.key">
          <div class="title-content">
            <p class="title">{{ spec.key }}</p>
          </div>
          <div class="sku-content">
            <van-tag
                class="sku-tag"
                :class="{activeTag:selectedSpecs[spec.key] === value}"
                v-for="value in spec.values"
                :key="value"
                size="large"
                color="#F7F7F9"
                @click="selectSpec(spec.key, value)"
            >
              {{ value }}
            </van-tag>
          </div>
        </div>
      </div>
      <div>
        <div style="font-size:16px;position: fixed;left:50%;transform: translateX(-50%);bottom:50px;"
             @click="handlePayment">
          <span>{{paymentChecked?paymentChecked==1?'微信支付':'支付宝支付':'请选择支付方式'}}</span>
          <van-icon name="arrow"/>
        </div>
        <van-goods-action>
          <van-goods-action-button color="rgba(0,0,0,0.8)" type="warning" text="打开岘视" id="openxsflag"/>
          <van-goods-action-button color="#456AFF" type="danger" @click="handleBuyNowStep1" text="立即购买"/>
        </van-goods-action>
      </div>
    </div>


    <van-action-sheet class="sku_popup" v-model="paymentShow" title="支付方式">
      <div class="content-wrapper">
        <!-- <div class="content">
          <div class="icon_txt">
            <span class="icon icon_wx"></span>
            <span class="txt">微信</span>
          </div>
          <van-radio-group v-model="paymentChecked" @change="handlePaymentChange">
            <van-radio name="1" label-disabled></van-radio>
          </van-radio-group>
        </div> -->
        <div class="content">
          <div class="icon_txt">
            <span class="icon icon_zfb"></span>
            <span class="txt">支付宝</span>
          </div>
          <van-radio-group v-model="paymentChecked" @change="handlePaymentChange">
            <van-radio name="2" label-disabled></van-radio>
          </van-radio-group>
        </div>
      </div>

    </van-action-sheet>

    <!-- 商品sku区域-->
  </div>
</template>
<script>

import {areaList} from '@vant/area-data';
import {
  getAddressList,
  getAddressAdd,
  getAddressDetail,
  getAddressUpdate,
  getAddressDelete,
  generateConfirmOrderInfo,
  generateOrderInfo,
  mallWebPayment
} from "@/api/product"
import {Toast} from "vant";
import JSEncrypt from "jsencrypt";

export default {
  props: {
    skuListValue: {
      type: Array,
      default: () => {
        return []
      }
    },
    productDetailData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      payparamstest: {
        // 2支付宝1微信
        orderId: undefined,
        type: 2,
      },
      encrypt: new JSEncrypt(),
      confirmparams: {
        orderToken:undefined,
        skuId:undefined,
        quantity:undefined,
        memberReceiveAddressId:undefined,
        payType:undefined,
        sourceType:0,
      },
      weixinparams: {
        appId: "",
        timeStamp: "",
        nonceStr: "",
        package: "",
        signType: "RSA",
        paySign: "",
      },

      browserflag: "",


      //支付方式弹层
      paymentShow: false,
      paymentChecked: '2',


      // 商品规格相关数据
      currentSku: {},          // 当前选中的SKU
      shopNums: 1,             // 购买数量
      specList: [],            // 规格列表
      selectedSpecs: {},       // 当前选中的规格


      //sku收货人信息
      currentContact: {},
      //打开地址列表popup
      showAreaList: false,
      updateInfo: {},
      //地址列表  当前选中的Id
      chosenContactId: undefined,
      //地址列表数据
      list: [],
      //地址列表 新增修改弹窗控制显示隐藏
      areaListEditShow: false,
      //地址列表 新增修改 弹窗标题
      areaListEditTitle: undefined,
      //省 市 区 数据
      areaList,


    }
  },
  created() {
    this.initSpecData();
    this.getAddressListData();

  },
  computed: {
    // 计算当前价格（考虑数量）
    calculatedPrice() {


      // 确保当前SKU存在
      if (!this.currentSku.price) return '0.00';

      // 计算总价 = 单价 × 数量
      const totalPrice = this.currentSku.price * this.shopNums;

      // 格式化为两位小数
      return totalPrice.toFixed(2);
    }
  },
  methods: {
    //立即购买
    handleBuyNowStep1() {
          if(!this.currentContact.name||!this.currentContact.tel){
           Toast('请选择收货地址')
           return
      }
      const quantity = this.shopNums
      const skuId = this.currentSku.id
      generateConfirmOrderInfo({quantity, skuId}).then(res => {
        this.confirmparams.orderToken = res.data.data.orderToken;
        this.confirmparams.skuId = skuId;
        this.confirmparams.quantity = quantity;
        this.confirmparams.memberReceiveAddressId = this.chosenContactId;
        this.confirmparams.payType = this.paymentChecked;
        this.handleBuyNowStep2();
      }).catch(error => {
        Toast.fail('支付失败!')
      })


    },
    handleBuyNowStep2() {


      generateOrderInfo({...this.confirmparams}).then(res => {
        console.log(res, "订单", res.data.data.order.id);
        this.payparamstest.orderId = res.data.data.order.id;
        this.payparamstest.type = this.paymentChecked
        this.handleBuyNowStep3();
      }).catch(error => {
        Toast.fail('支付失败!')
      })




    },

    handleBuyNowStep3() {
      mallWebPayment({...this.payparamstest}).then(res => {
        const ua = navigator.userAgent.toLowerCase();
        if (ua.includes("alipayclient") || ua.includes("alipay")) {
          this.browserflag = "ali";
        } else if (ua.includes("micromessenger")) {
          this.browserflag = "wx";
        } else {
          this.browserflag = "other";
        }
        if (this.payparamstest.type == 1) {
          if (this.payparamstest.type == 1 && this.browserflag == "wx") {
            // 微信内置浏览器的回调函数
            console.log("微信内置", res);
            this.weixinparams.appId = res.data.result.appid;
            this.weixinparams.timeStamp = res.data.result.timestamp;
            this.weixinparams.nonceStr = res.data.result.noncestr;
            this.weixinparams.package = res.data.result.packageValue;
            this.weixinparams.paySign = res.data.result.sign;
            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener(
                    "WeixinJSBridgeReady",
                    this.onBridgeReady,
                    false
                );
              } else if (document.attachEvent) {
                document.attachEvent(
                    "WeixinJSBridgeReady",
                    this.onBridgeReady
                );
                document.attachEvent(
                    "onWeixinJSBridgeReady",
                    this.onBridgeReady
                );
              }
            } else {
              this.onBridgeReady();
            }
          } else if (
              this.payparamstest.type == 1 &&
              this.browserflag != "wx"
          ) {
            //微信支付外置浏览器
            console.log("微信外置", res);
          }
        } else {
          // 支付宝支付
          const div = document.createElement("div");
          div.innerHTML = res.data.result;
          document.body.appendChild(div);
          document.forms[0].submit();
        }
      }).catch(error => {
        Toast.fail('支付失败!')
      })

    },
    onBridgeReady() {
      WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          this.weixinparams,
          function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              console.log(res, "支付成功的回调函数");
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
            }
          }
      );
    },
    handlePaymentChange() {
      if (this.paymentShow) {
        this.paymentShow = false;
      }

    },
    handlePayment() {
      this.paymentShow = true;
    },
    // 初始化规格数据
    initSpecData() {
      // 创建规格映射对象
      const specMap = {};

      // 遍历所有SKU，提取规格属性
      this.skuListValue.forEach(sku => {
        // 解析规格数据
        const specData = typeof sku.spData === 'string'
            ? JSON.parse(sku.spData)
            : sku.spData;

        // 收集规格属性及其可选值
        specData.forEach(item => {
          if (!specMap[item.key]) {
            specMap[item.key] = new Set();
          }
          specMap[item.key].add(item.value);
        });
      });

      // 转换规格映射为数组格式
      this.specList = Object.keys(specMap).map(key => ({
        key,
        values: Array.from(specMap[key])
      }));

      // 初始化选中规格（选择第一个SKU的规格）
      const firstSku = this.skuListValue[0];
      const firstSpecData = typeof firstSku.spData === 'string'
          ? JSON.parse(firstSku.spData)
          : firstSku.spData;

      firstSpecData.forEach(item => {
        this.$set(this.selectedSpecs, item.key, item.value);
      });

      // 设置当前SKU
      this.currentSku = firstSku;
    },

    // 选择规格
    selectSpec(key, value) {
      // 更新选中的规格
      this.$set(this.selectedSpecs, key, value);

      // 查找匹配的SKU
      const matchedSku = this.findMatchingSku();

      // 更新当前SKU
      if (matchedSku) {
        // 保留当前数量，但确保不超过新SKU的库存
        this.currentSku = matchedSku;

        // 检查数量是否超过新SKU的库存
        if (this.shopNums > matchedSku.stock) {
          this.shopNums = matchedSku.stock;
        }
      } else {
        // 如果没有匹配的SKU，显示提示
        Toast('该规格组合暂时缺货');
      }
    },


    // 处理数量超过限制的情况
    onOverlimit(action) {
      if (action === 'plus') {
        Toast(`最多只能购买${this.currentSku.stock}件`);
      } else if (action === 'minus') {
        Toast(`至少购买1件`);
      }
    },


    // 查找匹配的SKU
    findMatchingSku() {
      return this.skuListValue.find(sku => {
        const specData = typeof sku.spData === 'string'
            ? JSON.parse(sku.spData)
            : sku.spData;

        // 检查是否所有规格都匹配
        return Object.entries(this.selectedSpecs).every(([specKey, specValue]) => {
          return specData.some(item => item.key === specKey && item.value === specValue);
        });
      });
    },

    //默认展示列表
    getViewArea() {
      this.currentContact = this.list.find(v => v.isDefault)
      if (this.currentContact) {
        this.chosenContactId = this.currentContact.id
      } else {
        this.currentContact = this.list[0]
        this.chosenContactId = this.list[0].id
      }


    },
    //获取地址列表
    getAddressListData() {
      getAddressList().then(res => {


        this.list = res.data.data.map(item => {
          return {
            id: item.id,
            name: item.name,
            tel: item.phoneNumber,
            address: item.province + item.city + item.region + item.detailAddress,
            isDefault: item.defaultStatus === 1,

          }
        })


        if (this.list.length > 0) {
          this.getViewArea();
        } else {
          this.chosenContactId = undefined
        }


      })
    },
    //新增地址
    handleAddArea(formData) {
      let {
        id,
        name,
        tel: phoneNumber,
        areaCode,
        addressDetail: detailAddress,
        isDefault: defaultStatus,
        province,
        city,
        county: region
      } = formData;
      defaultStatus = defaultStatus ? 1 : 0;
      if (id) {
        getAddressUpdate(id, {
          name,
          phoneNumber,
          areaCode,
          detailAddress,
          defaultStatus,
          province,
          city,
          region
        }).then(res => {
          Toast({
            type: "success",
            message: "修改成功",
          });
          this.areaListEditShow = false;
          this.getAddressListData();
        })
      } else {
        getAddressAdd({name, phoneNumber, areaCode, detailAddress, defaultStatus, province, city, region}).then(res => {

          Toast({
            type: "success",
            message: "添加成功",
          });
          this.areaListEditShow = false;
          this.getAddressListData();
        })
      }


    },
    //删除地址
    handleDelArea(formData) {
      const {id} = formData;
      getAddressDelete(id).then(res => {
        Toast({
          type: "success",
          message: "删除成功",
        });
        this.areaListEditShow = false;
        this.getAddressListData();

      })
    },


    //sku地址信息跳转到地址列表
    handleLinkAreaList() {
      this.showAreaList = true;
    },
    //地址列表顶部导航栏 返回按钮
    onClickLeft() {
      this.showAreaList = false
    },
    //地址列表顶部导航栏 搜索按钮
    onClickRight() {
      Toast('搜索按钮');
    },
    //关闭弹窗
    handleAreaDialog() {
      this.areaListEditShow = false;
    },
    //地址列表顶部导航栏 新建联系人按钮
    handleAreaListAdd() {
      this.updateInfo = {}
      this.areaListEditTitle = '添加收货人地址'
      this.areaListEditShow = true
    },
    //地址列表顶部导航栏 修改按钮
    handleAreaListEdit(data) {
      this.areaListEditTitle = '修改收货人地址'
      this.areaListEditShow = true
      const {id} = data
      getAddressDetail(id).then(res => {
        let {
          id,
          name,
          phoneNumber: tel,
          detailAddress: addressDetail,
          defaultStatus: isDefault,
          areaCode
        } = res.data.data
        isDefault = isDefault === 1
        this.updateInfo = {id, name, tel, addressDetail, isDefault, areaCode};

      })


    },
    //地址列表顶部导航栏 选择按钮
    handleAreaListSelect(item) {
      this.currentContact = item;


    }
  }
}
</script>

<style scoped>
.specification-detail :deep(.van-button--danger) {
  background-color: #5C7DFF;
  border: 1px solid #5C7DFF;
}

.product-sku-wrapper {
  padding-left: 0.3rem;
}

.pic-price-msg-wrapper {
  display: flex;
}

.pic-price-msg-wrapper :deep(.van-image) {
  margin-top: 0.48rem;
}

.pic-price-msg-wrapper .price-msg {
  margin-left: 0.26rem;
}

.pic-price-msg-wrapper .price-msg .price-content {
  margin-top: 0.38rem;
  display: flex;
  justify-content: flex-start;
}

.pic-price-msg-wrapper .price-msg .price-content .icon {
  font-weight: 600;
  font-size: 0.26rem;
  color: #FA2C19;
  line-height: 0.6rem;
  font-style: normal;
}

.pic-price-msg-wrapper .price-msg .price-content .price {
  font-weight: 600;
  font-size: 0.5rem;
  color: #FA2C19;
  line-height: 0.6rem;
  font-style: normal;
}

.pic-price-msg-wrapper .price-msg .price-content .txt {
  margin-left: 0.1rem;
  font-weight: 400;
  font-size: 0.24rem;
  color: #FA2C19;
  line-height: 0.65rem;
  font-style: normal;
}

.pic-price-msg-wrapper .sale-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pic-price-msg-wrapper .sale-content .txt {
  font-weight: 400;
  font-size: 0.26rem;
  color: #ABABAB;

  text-align: left;
  font-style: normal;
}

.pic-price-msg-wrapper .sale-content .segmentation {
  margin: 0 0.3rem;
  width: 0.02rem;
  height: 0.2rem;
  background-color: #ABABAB;
}

.pic-price-msg-wrapper .nums-content {
  margin-top: 0.2rem;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.pic-price-msg-wrapper .nums-content .txt {
  margin-left: 0.23rem;
  font-weight: 400;
  font-size: 0.24rem;
  color: #ABABAB;
  font-style: normal;
}

.sku-msg-wrapper {
  margin-top: 0.37rem;
}


.sku-msg-wrapper :deep(.sku-tag) {
  border: 2px solid transparent;
  color: #333333 !important;
  padding: 0.1rem 0.15rem;
}

.sku-msg-wrapper :deep(.activeTag) {
  border: 2px solid #2F59FE;
  color: #333333 !important;
  padding: 0.1rem 0.15rem;
}

.sku-msg-wrapper .sku-item .title-content {
  margin-bottom: 0.1rem;
}

.sku-msg-wrapper .sku-item {
  margin-top: 0.46rem;
}

.sku-msg-wrapper .sku-item .title-content .title {

  font-weight: 500;
  font-size: 0.32rem;
  color: #333333;
  line-height: 0.45rem;
  font-style: normal;
}

.sku-msg-wrapper .sku-content {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.sku-msg-wrapper .sku-content :deep(.van-tag) {
  margin-right: 0.2rem;
}

:deep(.sku_popup) .content-wrapper {
  padding-top: 0.3rem;
  padding-bottom: 2.9rem;
}

:deep(.sku_popup) .content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0.3rem 0.4rem 0.3rem;
}

:deep(.sku_popup) .content .icon_txt {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.sku_popup) .content .icon {
  width: 0.6rem;
  height: 0.6rem;
}

:deep(.sku_popup) .content .icon_wx {

  background: url("@/assets/images/wx_payment.png") no-repeat 0 0/100% 100%;
}

:deep(.sku_popup) .content .icon_zfb {

  background: url("@/assets/images/zfb_payment.png") no-repeat 0 0/100% 100%;
}

:deep(.sku_popup) .content .txt {
  font-size: 0.28rem;
  margin-left: 6px;
}

</style>